package com.mrdeer.config.thread;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 增大线程数提高吞吐量
 * 提升由于线程数不足问题导致的高并发问题
 *
 * @author xie jianchu
 */
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "server")
public class ThreadConfig {

    @Setter
    private ThreadProperty thread;

    private final AtomicInteger threadPoolAtomic = new AtomicInteger(1);
    private final AtomicInteger scheduledThreadPoolAtomic = new AtomicInteger(1);

    /**
     * 默认线程池
     */
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数目
        executor.setCorePoolSize(thread.getCorePoolSize());
        //指定最大线程数
        executor.setMaxPoolSize(thread.getMaximumPoolSize());
        //队列中最大的数目
        executor.setQueueCapacity(50);
        //线程名称前缀
        executor.setThreadNamePrefix(thread.getPrefix());
        //rejection-policy:当pool已经达到max size的时候，如何处理新任务
        //CALL_RUNS:不在新线程中执行任务，而是由调用者所在的线程来执行
        //对拒绝task的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后的最大存活时间
        executor.setKeepAliveSeconds(thread.getKeepAliveTime());
        //加载
        executor.initialize();
        return executor;
    }

    /**
     * ScheduledThreadPoolExecutor ThreadPoolExecutor
     *
     * @return
     */
    @Bean
    public ScheduledThreadPoolExecutor scheduledThreadPoolExecutor() {
        return new ScheduledThreadPoolExecutor(thread.getCorePoolSize(),
                (r) -> new Thread(r, "[ScheduledThreadPoolExecutor]" + thread.getPrefix() + scheduledThreadPoolAtomic.getAndIncrement()),
                (r, e) -> log.error("ScheduledThreadPoolExecutor Rejected"));
    }
}
